import PyQt5.QtCore

from .mainUI import Ui_MainWindow
from .ble_deal import myBLE
from PyQt5 import QtWidgets, QtBluetooth, QtCore
from PyQt5.QtWidgets import QMessageBox
import datetime


class BluetoothLowPower(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(BluetoothLowPower, self).__init__()
        self.setupUi(self)
        self.my_ble = myBLE()

        self.button_search.clicked.connect(self.scan_device)
        self.button_connect_device.clicked.connect(self.connect_device)
        self.button_connect_service.clicked.connect(self.connect_service)
        self.button_read_characteristic.clicked.connect(self.read_characteristic)
        self.my_ble.DiscoverySignal.connect(self.discovery_device)
        self.my_ble.ServiceFoundSignal.connect(self.discovery_service)
        self.my_ble.CharacteristicSignal.connect(self.characteristic_changed)
        self.my_ble.ReadSignal.connect(self.write_text)
        self.my_ble.TestSignal.connect(self.write_test_info)

    def discovery_device(self, info: QtBluetooth.QBluetoothDeviceInfo):
        self.comboBox_device.addItem(info.name(), info)

    def discovery_service(self, uuid: QtBluetooth.QBluetoothUuid):
        self.comboBox_service.addItem(uuid.toString(), uuid)

    def scan_device(self):
        self.comboBox_device.clear()
        rtn = self.my_ble.start_scan()
        if rtn is not None:
            QMessageBox.critical(self, "Error", rtn)

    def connect_device(self):
        self.comboBox_service.clear()
        data = self.comboBox_device.itemData(self.comboBox_device.currentIndex())
        self.my_ble.connect_device(data)

    def connect_service(self):
        self.comboBox_characteristic.clear()
        data = self.comboBox_service.itemData(self.comboBox_service.currentIndex())
        self.my_ble.connect_service(data)

    def characteristic_changed(self, ch: QtBluetooth.QLowEnergyCharacteristic):
        self.comboBox_characteristic.addItem(ch.name() + " - " + ch.uuid().toString(), ch)

    def read_characteristic(self):
        data = self.comboBox_characteristic.itemData(self.comboBox_characteristic.currentIndex())
        self.my_ble.read_characteristic(data)

    def write_text(self, data: QtCore.QByteArray):
        t = datetime.datetime.now()
        self.textEdit.append(str(t) + " --- " + str(data))
        print('原始:  ',data[0],' - ',data[1])
        data = bytearray((3,9))
        print('Byte_arry:   ',data) 
#        int(data_yuan[i], 16)
#        print('bin:  ',bin(data[0]),' - ',bin(data[1])) 

    def write_test_info(self, data: str):
        self.textEdit.append(data)
        print ('write_test_info',data)
